package com.club.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.club.bean.Club;
import com.club.service.ClubService;
import com.club.util.JWTUtil;
import com.club.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("club")
@CrossOrigin//允许跨越
public class ClubController {
    // 自动注入 ClubService 依赖，需要提前定义好 ClubService 接口及实现
    @Autowired
    ClubService clubService;

    @GetMapping("list")
    public Result getlist() {
        List<Club> list = clubService.list();
        return Result.success(list);
    }

    @PostMapping("add")
    public Result add(@RequestBody Club club) {
        club.setStatus("正常");
        clubService.save(club);
        Club savedClub = clubService.getById(club.getClub_id());
        return Result.success("保存成功", savedClub);
    }

    @DeleteMapping("/{club_id}")
    public Result delete(@PathVariable("club_id") String club_id) {
        boolean b = clubService.removeById(club_id);
        if (b) {
            return Result.success("删除成功");
        } else {
            return Result.error(201, "删除失败");
        }
    }

    @PutMapping
    public Result edit(@RequestBody Club club) {
        boolean b = clubService.saveOrUpdate(club);
        Club updatedClub = clubService.getById(club.getClub_id());
        if (b) {
            return Result.success("保存成功", updatedClub);
        } else {
            return Result.error(201, "修改失败");
        }
    }

    @GetMapping("page")
    public Result getPage(Page page, @RequestParam(value = "searchText", required = false) String searchText) {
        System.out.println(searchText);
        IPage<Club> result = null;
        if (searchText == null || searchText.trim().isEmpty()) {
            result = clubService.page(page);
        } else {
            QueryWrapper<Club> wrapper = new QueryWrapper<>();
            wrapper.like("club_name", searchText);
            wrapper.or();
            wrapper.like("category", searchText);

            result = clubService.page(page, wrapper);
        }
        return Result.success(result);
    }

//    //  Club 登录逻辑不太适用
//    @PostMapping("login")
//    public Result login(Club club) {
//        // 这里原 Tadmin 的 phone 等逻辑不适用 Club，假设根据 club_name 等做类似认证，需重新实现
//
//        Club club_data = clubService.selectByName(club.getClub_name());
//        if (club_data != null) {
//
//            boolean check = true;
//            if (check) {
//                String token = JWTUtil.getToken();
//                return Result.success("登陆成功", token);
//            }
//        }
//        return Result.error(401, "认证失败");
//    }
}
